<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\order\Order;
use app\models\order\OrderOffline;
use app\models\system\SetApp;
use app\models\user\User;
use app\services\Upload as Service;

class UploadController extends H5Controller
{
    // 上传打款凭证
    public function actionExecute()
    {
        $result = Service::uploadImage('offline');

        if ($result) {

            // 处理订单
            $order_id = $this->post('order_id');
            $order = Order::findOne(['id' => $order_id, 'user_id' => $this->user->id]);
            if (!$order) {
                return $this->fail('操作失败');
            }
            if ($order->status != Order::$statusMapping['NON_PAYMENT']) {
                return $this->fail('已经支付,不需要再上传凭证');
            }
            $image_id = $result['id'];
            $model = new OrderOffline();
            $model->order_id = $order_id;
            $model->image_id = $image_id;
            if ($model->save()) {
                $result['id'] = $model->id;
                return $this->success($result, '上传成功');
            }
        } else {
            return $this->fail('上失败,' . Service::getLastError());
        }
    }

    public function actionGetList()
    {
        $order_id = $this->post('order_id');
        $order = Order::findOne(['id' => $order_id, 'user_id' => $this->user->id]);

        if (!$order) {
            return $this->fail('操作失败');
        }

        $list = OrderOffline::find()
            ->where(['order_id' => $order->id])
            ->with(['image'])
            ->asArray()
            ->all();
        $urls = [];
        foreach ($list as $item) {
            if ($item['image'] && $item['image']['path']) {
                array_push($urls, [
                    'path' => $item['image']['path'],
                    'id' => $item['id'],
                ]);
            }
        }

        // 收款码
        $qrcode = SetApp::getLastOne();
        $qrcode = $qrcode['money_qrcode'];
        // 返回给前端, 由于加密, 需要这样处理
        if ($qrcode) {
            $qrcode = $qrcode->toArray();
        }

        return $this->successEncode([
        // return $this->success([
            'list' => $urls,
            'qrcode' => $qrcode
        ]);
    }

    public function actionRemoveImage()
    {
        $id = $this->post('id');

        $model = OrderOffline::findOne(['id' => $id]);
        if ($model && $model->delete()) {
            return $this->success();
        }

        return $this->fail('操作失败');
    }

    // 修改头像
    public function actionAvatar()
    {
        $result = Service::uploadImage('avatar');

        if ($result) {

            $model = User::findOne(['id' => $this->user->id]);
            $model->avatar = $result['full_name'];
            $model->av = 1;
            $model->save();


            return $this->success($result, '上传成功');

        } else {
            return $this->fail('上失败,' . Service::getLastError());
        }
    }
}